<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="referrer" content="no-referrer"/>
    <title>智能电影推荐系统 - 电影详情</title>
    <!-- 新 Bootstrap5 核心 CSS 文件 -->
    <link rel="stylesheet"
          href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://unpkg.com/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/common.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark px-3" style="background-color: #0d6efd;">
    <div class="container-fluid">
        <a class="navbar-brand" href="index.html">智能电影推荐系统</a>
        <div class="d-flex" id="userInfoArea">
            <!-- 用户信息区域将通过JavaScript动态填充 -->
        </div>
    </div>
</nav>

<div class="container mt-5" id="movieDetailContainer">
    <!-- 电影详情将通过JavaScript动态填充 -->
</div>

<!-- 最新的 Bootstrap5 核心 JavaScript 文件 -->
<script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/common.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const urlParams = new URLSearchParams(window.location.search);
        const movieId = urlParams.get('id');
        const userInfoArea = document.getElementById('userInfoArea');
        const movieDetailContainer = document.getElementById('movieDetailContainer');

        if (movieId) {
            axios.get(`${API_BASE_URL}/movie/${movieId}`)
                .then(response => {
                    const movie = response.data.movie;
                    movieDetailContainer.innerHTML = `
                            <div class="row">
                                <div class="col-md-4">
                                    <img src="${movie.poster}" class="img-fluid rounded" alt="${movie.title}" referrer="no-referrer">
                                </div>
                                <div class="col-md-8">
                                    <h2>${movie.title}</h2>
                                    <p><strong>类型:</strong> ${movie.type}</p>
                                    <p><strong>评分:</strong> ${movie.rating}</p>
                                    <p><strong>上映年份:</strong> ${movie.year}</p>
                                    <p><strong>地区:</strong> ${movie.region}</p>
                                    <p><strong>导演:</strong> ${movie.director}</p>
                                    <p><strong>简介:</strong> <a href="#" id="deepseekLink">看看DeepSeek怎么说</a></p>
                                    <div id="aiDescription" class="mt-2"></div>
                                </div>
                            </div>
                        `;

                    // AI简介 - 使用事件委托
                    document.getElementById('movieDetailContainer').addEventListener('click', function (e) {
                        if (e.target && e.target.id === 'deepseekLink') {
                            e.preventDefault();
                            // 显示加载提示
                            document.getElementById('aiDescription').innerHTML = '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div>';

                            axios.get(`${API_BASE_URL}/ai_des?title=${encodeURIComponent(movie.title)}&year=${movie.year}&director=${encodeURIComponent(movie.director)}`)
                                .then(response => {
                                    document.getElementById('aiDescription').innerHTML = response.data.description + '<div class="mt-2"><button class="btn btn-outline-primary" id="playBtn"><i class="bi bi-play-fill"></i> 播放</button></div>';

                                    // 添加播放按钮事件
                                    let isPlaying = false;
                                    let audio = null;
                                    const playBtn = document.getElementById('playBtn');
                                    playBtn.addEventListener('click', function () {
                                        if (!isPlaying) {
                                            playBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 加载中';
                                            playBtn.disabled = true;
                                            isPlaying = true;

                                            axios.get(`${API_BASE_URL}/tts?text=${encodeURIComponent(response.data.description)}`, {
                                                responseType: 'arraybuffer'
                                            })
                                                .then(response => {
                                                    if (response.status === 200) {
                                                        const audioBlob = new Blob([response.data], {type: 'audio/mpeg'});
                                                        const audioUrl = URL.createObjectURL(audioBlob);
                                                        audio = new Audio(audioUrl);
                                                        playBtn.innerHTML = '<i class="bi bi-pause-fill"></i> 播放中，点击停止';
                                                        playBtn.disabled = false;
                                                        audio.play().catch(error => {
                                                            console.error('播放失败:', error);
                                                        });
                                                        audio.onended = () => {
                                                            URL.revokeObjectURL(audioUrl);
                                                            playBtn.innerHTML = '<i class="bi bi-play-fill"></i> 播放';
                                                            isPlaying = false;
                                                        };
                                                    }
                                                })
                                                .catch(error => {
                                                    console.error('Error:', error);
                                                    playBtn.innerHTML = '<i class="bi bi-play-fill"></i> 播放';
                                                    playBtn.disabled = false;
                                                    isPlaying = false;
                                                });
                                        } else {
                                            if (audio) {
                                                audio.pause();
                                                audio = null;
                                            }
                                            playBtn.innerHTML = '<i class="bi bi-play-fill"></i> 播放';
                                            isPlaying = false;
                                        }
                                    });

                                    /*playBtn.addEventListener('click', function () {
                                        if (!isPlaying) {
                                            // 开始播放
                                            utterance = new SpeechSynthesisUtterance(response.data.description);
                                            utterance.lang = 'zh-CN';
                                            speechSynthesis.speak(utterance);
                                            
                                            // 更新按钮状态
                                            playBtn.innerHTML = '<i class="bi bi-pause-fill"></i> 播放中，点击停止';
                                            isPlaying = true;
                                            
                                            // 播放结束时恢复按钮状态
                                            utterance.onend = function() {
                                                playBtn.innerHTML = '<i class="bi bi-play-fill"></i> 播放';
                                                isPlaying = false;
                                            };
                                        } else {
                                            // 停止播放
                                            speechSynthesis.cancel();
                                            playBtn.innerHTML = '<i class="bi bi-play-fill"></i> 播放';
                                            isPlaying = false;
                                        }
                                    });*/
                                })
                                .catch(error => {
                                    console.error('Error:', error);
                                    document.getElementById('aiDescription').innerHTML = '<div class="alert alert-danger">获取AI简介失败</div>';
                                });
                        }
                    });


                    // 添加分割线和推荐标题
                    movieDetailContainer.innerHTML += `
                            <hr class="my-4">
                            <h3>相关电影推荐</h3>
                            <div id="recommendedMovies" class="row"></div>
                        `;

                    // 获取推荐电影
                    axios.get(`${API_BASE_URL}/rec_by_movie?movie=${encodeURIComponent(movie.title)}`)
                        .then(response => {
                            const recommendedMovies = response.data.movies;
                            const recommendedMoviesContainer = document.getElementById('recommendedMovies');

                            recommendedMovies.forEach(movie => {
                                recommendedMoviesContainer.innerHTML += `
                                        <div class="col-md-2 mb-2">
                                            <div class="card h-100">
                                                <img src="${movie.poster}" class="card-img-top" style="height:200px;object-fit:cover" alt="${movie.title}" referrer="no-referrer">
                                                <div class="card-body p-1">
                                                    <h6 class="card-title mb-0" style="font-size:0.8rem">${movie.title}</h6>
                                                    <p class="card-text mb-0" style="font-size:0.7rem">评分: ${movie.rating}</p>
                                                    <a href="movie.html?id=${movie.id}" class="btn btn-sm btn-primary mt-2 w-100">查看详情</a>
                                                </div>
                                            </div>
                                        </div>
                                    `;
                            });
                        });
                })
                .catch(error => console.error('Error:', error));
        } else {
            movieDetailContainer.innerHTML = '<div class="alert alert-danger">未找到电影信息</div>';
        }

        const user = JSON.parse(localStorage.getItem('user'));
        if (user) {
            // 已登录状态
            userInfoArea.innerHTML = `
                    <span class="navbar-text me-3 text-white">欢迎您，</span>
                    <a href="profile.html" class="navbar-text text-white">${user.nickname}</a>
                    <span class="navbar-text mx-3">|</span>
                    <a href="#" class="navbar-text text-white" id="logoutBtn">退出</a>
                `;

            document.getElementById('logoutBtn').addEventListener('click', function () {
                localStorage.removeItem('user');
                window.location.href = 'index.html';
            });
        } else {
            // 未登录状态
            userInfoArea.innerHTML = '<a href="login.html" class="navbar-text text-white">登录</a>';
        }
    });
</script>
</body>
</html>